package com.jiangdg.demo

import android.content.Context
import android.database.ContentObserver
import android.media.AudioManager
import android.os.Handler
import android.provider.Settings
import android.util.Log

class VolumeObserver(handler: Handler, private val context: Context, private val onVolumeChangeListener: OnVolumeChangeListener) : ContentObserver(handler) {

    private val audioManager = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager
    private var previousVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC)


    override fun onChange(selfChange: Boolean) {
        super.onChange(selfChange)
        val currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC)
        if (currentVolume > previousVolume) {
            onVolumeChangeListener.onChange(true)
            Log.d("VolumeObserver", "Volume Up")
        } else if (currentVolume < previousVolume) {
            Log.d("VolumeObserver", "Volume Down")
            onVolumeChangeListener.onChange(false)
        }
        previousVolume = currentVolume
    }

    interface OnVolumeChangeListener{
        fun onChange(volumeUp: Boolean)
    }
}
